@file:OptIn(ExperimentalMaterial3Api::class)

package com.ly.chatsimple.ui.chat

import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.requiredHeight
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.sharp.ArrowBack
import androidx.compose.material.icons.sharp.Face
import androidx.compose.material.icons.sharp.Settings
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.ListItem
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.drawBehind
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Paint
import androidx.compose.ui.graphics.PaintingStyle
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavController
import androidx.navigation.compose.rememberNavController
import com.ly.chatsimple.R
import com.ly.chatsimple.ui.chat.state.ChatRecord
import com.ly.chatsimple.ui.chat.viewmodel.ChatViewModel

private const val BOTTOM_MENU_HEIGHT = 65 //unit dp

@Composable
fun ChatPage(chatViewModel: ChatViewModel = viewModel(), navController: NavController) {
    Scaffold(
        topBar = {
            TopAppBar(title = {
                Row(
                    horizontalArrangement = Arrangement.Center,
                    modifier = Modifier.fillMaxWidth()
                ) {
                    Text(text = "ChatRoom")
                }
            }, navigationIcon = {
                IconButton(onClick = {
                    navController.popBackStack()
                }) {
                    Icon(
                        imageVector = Icons.Sharp.ArrowBack,
                        contentDescription = "arrowBack"
                    )
                }
            }, actions = {
                IconButton(onClick = { }) {
                    Icon(imageVector = Icons.Sharp.Settings, contentDescription = "setting")
                }
            })
        }
    ) {
        Column(
            modifier = Modifier
                .padding(it)
                .fillMaxSize()
        ) {
            ChatList(
                modifier = Modifier
                    .fillMaxWidth()
                    .weight(1f),
                chatViewModel
            )
            BottomMenu(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(BOTTOM_MENU_HEIGHT.dp)
                    .padding(bottom = 15.dp, start = 5.dp),
                chatViewModel
            )
        }

    }
}

@Composable
fun ChatList(modifier: Modifier, chatViewModel: ChatViewModel) {
    LazyColumn(
        modifier = modifier,
        state = chatViewModel.recordListState
    ) {
        items(chatViewModel.recordList) { record ->
            ListItem(headlineContent = {
                RecordItem(record = record)
            })
        }
    }
}

@Composable
fun BottomMenu(
    modifier: Modifier = Modifier,
    chatViewModel: ChatViewModel
) {
    Row(
        modifier = modifier,
        horizontalArrangement = Arrangement.SpaceBetween
    ) {
        var inputContent by remember {
            mutableStateOf("")
        }
        TextField(
            value = inputContent,
            onValueChange = { value ->
                inputContent = value
            },
            modifier = Modifier
                .fillMaxHeight()
                .weight(1f),
            keyboardOptions = KeyboardOptions(
                imeAction = ImeAction.Send
            ),
            keyboardActions = KeyboardActions(onSend = {
                chatViewModel.onSend(inputContent)
                inputContent = ""
            })
        )
        IconButton(onClick = {

        }) {
            Icon(
                imageVector = Icons.Sharp.Face,
                contentDescription = "emoji",
                tint = Color.DarkGray
            )
        }
    }
}

@Composable
fun RecordItem(record: ChatRecord) {
    Box(modifier = Modifier.drawBehind {
        val canvas = drawContext.canvas
        val height = drawContext.size.height
        val width = drawContext.size.width
        val paint = Paint()
        paint.color = Color.LightGray
        paint.style = PaintingStyle.Fill
        paint.strokeWidth = 1.dp.value
        val paddingWidth = 16.dp.value
        val yOffset = 5.dp.value + height
        val offset1 = Offset(paddingWidth, yOffset)
        val offset2 = Offset(width - paddingWidth, yOffset)
        canvas.drawLine(offset1, offset2, paint)
    }) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .requiredHeight(60.dp)
                .padding(vertical = 5.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            if (!record.isSender) {
                Avatar(isSender = false)
            }
            Column(
                verticalArrangement = Arrangement.SpaceEvenly,
                horizontalAlignment = if (record.isSender) Alignment.End else Alignment.Start,
                modifier = Modifier
                    .fillMaxHeight()
                    .padding(5.dp)
                    .weight(1f)
            ) {
                Text(text = record.date)
                Text(text = record.content)
            }
            if (record.isSender) {
                Avatar(isSender = true)
            }
        }
    }
}

@Composable
fun Avatar(isSender: Boolean) {
    val avatar =
        painterResource(id = if (isSender) R.mipmap.avatar1 else R.mipmap.avatar2)
    Image(
        painter = avatar, contentDescription = "avatar", modifier = Modifier
            .size(45.dp)
            .clip(RoundedCornerShape(90.dp))
    )
}

@Preview
@Composable
private fun ChatPagePre() {
    ChatPage(navController = rememberNavController())
}

@Preview
@Composable
private fun RecordItemPre() {
    Box(
        modifier = Modifier
            .background(Color.Gray)
            .padding(10.dp)
    ) {
        Box(modifier = Modifier.background(Color.White)) {
            val record = ChatRecord(isSender = true, content = "实打实打算")
            RecordItem(record)
        }
    }
}